import { MciSelect } from '@/components/base';
import { CalcTypeSelector } from '@/components/business/DictSelector/CalcType';
import { OperatorSelector } from '@/components/business/DictSelector/Operator';
import { PropType } from 'vue';
import CondValue from '../CondValue/index.vue';
import type { ICondition, ILeft } from '../type';
import { EOperator, ERightType } from '../type';
import { useFormMode } from '@/components/base/Form/mode';

export const Condition = defineComponent({
  props: {
    conditionValue: {
      type: Object as PropType<ICondition>,
      default: () => ({})
    },
    leftOptions: {
      type: Array as PropType<ILeft[]>,
      default: () => []
    }
  },
  emits: ['condValueChange', 'leftChange', 'operatorChange', 'rightTypeChange'],
  setup(props, { emit }) {
    const left = ref(props.conditionValue.left);
    const operator = ref(props.conditionValue.operator);
    const rightType = ref(props.conditionValue.rightType);
    const right = ref(props.conditionValue.right);

    const formMode = useFormMode();

    const leftChange = (val: any) => {
      left.value = val;
      emit('leftChange', val);
    };
    const operatorChange = (val: EOperator) => {
      operator.value = val;
      emit('operatorChange', val);
    };
    const rightTypeChange = (val: ERightType) => {
      rightType.value = val;
      emit('rightTypeChange', val);
    };
    // 值
    const valueChange = (val: any) => {
      emit('condValueChange', val);
    };
    watch(
      () => [props.conditionValue],
      () => {
        if (props.conditionValue) {
          left.value = props.conditionValue.left;
          operator.value = props.conditionValue.operator;
          rightType.value = props.conditionValue.rightType;
          right.value = props.conditionValue.right;
        }
      },
      { immediate: true, deep: true }
    );

    return () => (
      <div class="flex items-center" style={{ overflowX: 'auto' }}>
        <MciSelect
          modelValue={left.value}
          list={props.leftOptions}
          filterable={true}
          class="px-4 shrink-0"
          onChange={leftChange}
        />
        <OperatorSelector
          modelValue={operator.value}
          placeholder="请选择运算符"
          class={{ 'px-4': true, ' min-w-[100px]':formMode?.mode === 'edit' }}
          onUpdate:modelValue={operatorChange}
        />
        {operator.value !== EOperator.IsEmpty && operator.value !== EOperator.IsNotEmpty && (
          <div class="flex items-center grow">
            <CalcTypeSelector modelValue={rightType.value} class="px-4" onUpdate:modelValue={rightTypeChange} />
            <CondValue
              class={'grow'}
              operator={operator.value}
              rightType={rightType.value}
              right={right.value}
              onCondValueChange={valueChange}
            />
          </div>
        )}
      </div>
    );
  }
});
